package fi.internetix.ck;

import org.w3c.dom.Node;
import org.w3c.tidy.DOMTextImpl;

public class TextNodePrinter extends HTMLNodePrinter {

  public void processNode(Node node, StringBuilder output) {
    DOMTextImpl textNode = (DOMTextImpl) node;
    String text = textNode.getNodeValue();
    if (text != null && text.length() > 0) {
      if (NodePrinterUtils.trim(text).length() > 0) {
        output.append(encodeNon7BitChars(text));
      }
    }
  }

  private String encodeNon7BitChars(String value) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < value.length(); i++) {
      char c = value.charAt(i);
      int ci = (int) c;
      if (ci <= 127) {
        sb.append(c);
      } else {
        sb.append("&#");
        sb.append(String.valueOf(ci));
        sb.append(';');
      }
    }
    return sb.toString();
  }

}
